package com.ice.app.system.auth.service;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ice.app.system.auth.vo.UiConfigVo;
import com.ice.app.system.entity.User;
import com.ice.app.system.mapper.MenuMapper;
import com.ice.app.system.mapper.UserMapper;
import com.ice.app.system.utils.ConfigUtils;
import com.ice.app.system.utils.SysDateUtils;
import com.iceframework.core.entity.Result;
import com.iceframework.core.support.cache.ICacheService;
import com.iceframework.core.support.security.entity.IJWTInfo;
import com.iceframework.core.support.security.util.JwtUtils;
import com.iceframework.core.utils.JsonUtils;

/**
 * 权限验证
 * @author Palo
 *
 */
@Service
public class AuthService {

	@Autowired
	private UserMapper userMapper;

	@Autowired
	private MenuMapper menuMapper;
	
	@Autowired
	private ICacheService cacheService;
	
	public static String TOKEN_PREFIX = "ICE:TOKEN:";
	public static String TOKEN_TEMP_PREFIX = "ICE:TOKEN:TEMP:";
	
	/**
	 * 登录
	 * @param user
	 * @return
	 */
	public String login(User user){
		String token = "";
		User auth = userMapper.selectByUsernameAndPassword(user.getUsername(), user.getPassword());
		if(auth!=null) {
			token = JwtUtils.generToken(auth.getUserId(), null, JsonUtils.convertObj2String(auth));
			cacheService.set(TOKEN_PREFIX+auth.getUserId() ,token,ICacheService.Thrity_Minutes);
		}
		return token;
	}
	
	/**
	 * 刷新token
	 * @param token
	 * @return
	 */
	public String refresh(String token){
		IJWTInfo jwtInfo = JwtUtils.getJWTInfoByToken(token);
		if(jwtInfo == null) {
			return null;
		}
		String userId = jwtInfo.getUserId();
		String refreshToken = JwtUtils.updateToken(token);
		//设置新token
		cacheService.set(TOKEN_PREFIX+userId ,refreshToken,ICacheService.Thrity_Minutes);
		//设置交换的Token,交换期间内10秒过期
		cacheService.set(TOKEN_TEMP_PREFIX+token ,refreshToken,10);
		return refreshToken;
	}
	
	/**
	 * 验证token是否过期（过期查看是否有交换）
	 * @param token
	 * @return
	 */
	public boolean validate(String token){
		try {
			IJWTInfo jwtInfo = JwtUtils.getJWTInfoByToken(token);
			String key = TOKEN_PREFIX+jwtInfo.getUserId();
			String temp = cacheService.get(key, String.class);
			if(StringUtils.isNotEmpty(temp)) {
				if(temp.equals(token)) {
					return true;
				}
			}
			if(StringUtils.isNotEmpty(temp)) {
				temp = cacheService.get(TOKEN_TEMP_PREFIX+token, String.class);
				if(StringUtils.isNotEmpty(temp)) {
					return true;
				}
			}
		} catch (Exception e) {
			return false;
		}
		return false;
	}
	
	/**
	 * 登录
	 * @param user
	 * @return
	 */
	public String generateTokenByUsername(String username){
		String token = "";
		User auth = userMapper.selectByUsername(username);
		if(auth!=null) {
			token = JwtUtils.generToken(auth.getUserId(), null, JsonUtils.convertObj2String(auth));
			cacheService.set(TOKEN_PREFIX+auth.getUserId() ,token,ICacheService.Thrity_Minutes);
		}
		return token;
	}
	
	/**
	 * 根据用户名创建Token
	 * @param username
	 * @return
	 * @throws Exception
	 */
	public Result createAuthenticationToken(String username) throws Exception {
		final String token = this.generateTokenByUsername(username);
		if (StringUtils.isNoneEmpty(token)) {
			// 获取资源
			List<String> resources = menuMapper.selectResourceByUserName(username);
			// 获取系统配置
			UiConfigVo uiConfig = getUiConfig();
			return Result.newOne().setCode("200").add("token", token).add("resources", resources).add("uiConfig", uiConfig).add("accessTime", System.currentTimeMillis());
		} else {
			return Result.newOne().setCode("401").add("token", null);
		}
	}
	
	/**
	 * 获取前端配置
	 * @return
	 */
	public UiConfigVo getUiConfig() {
		UiConfigVo uiConfigVo = new UiConfigVo();
		String uiVersionCache = ConfigUtils.getCacheConfig("UI_Version");
		uiVersionCache = uiVersionCache == null ? String.valueOf(SysDateUtils.getSysDatetime().getTime()) : uiVersionCache;
		uiConfigVo.setUiVersion(uiVersionCache);
		return uiConfigVo;
	}
	
}
